#! /usr/bin/env python

import datetime
import argparse

from simplemediawiki import build_user_agent

import ParabolaWiki
    
if __name__ == "__main__":
    aparser = argparse.ArgumentParser(description="Download pages from Parabola Wiki and optimize them for offline browsing")
    aparser.add_argument("--output-directory", type=str, required=True, help="Path where the downloaded pages should be stored.")
    aparser.add_argument("--force", action="store_true", help="Ignore timestamp, always download the page from the wiki.")
    aparser.add_argument("--clean", action="store_true", help="Clean the output directory after downloading, useful for removing pages deleted/moved on the wiki. Warning: any unknown files found in the output directory will be deleted!")
    aparser.add_argument("--safe-filenames", action="store_true", help="Force using ASCII file names instead of the default Unicode.")

    args = aparser.parse_args()
    if args.force:
        epoch = datetime.datetime.utcnow()
    else:
        # this should be the date of the latest incompatible change
        epoch = datetime.datetime(2016, 3, 3, 18, 0, 0)

    user_agent = build_user_agent(__file__, ParabolaWiki.__version__, ParabolaWiki.__url__)
    aw = ParabolaWiki.ParabolaWiki(user_agent=user_agent, safe_filenames=args.safe_filenames)
    optimizer = ParabolaWiki.Optimizer(aw, args.output_directory)

    downloader = ParabolaWiki.Downloader(aw, args.output_directory, epoch, cb_download=optimizer.optimize_url)
    aw.print_namespaces()
    for ns in ["0", "4", "12", "14"]:
        downloader.process_namespace(ns)

    downloader.download_images()
    downloader.download_css()

    if args.clean:
        downloader.clean_output_directory()
